package com.wbl.tijianssm.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.wbl.tijianssm.config.AliPayConfig;
import com.wbl.tijianssm.mapper.OrdersMapper;
import com.wbl.tijianssm.mapper.SetmealMapper;
import com.wbl.tijianssm.pojo.Orders;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private AliPayConfig aliPayConfig;

    @GetMapping ("/alipay")
    public void alipay(Integer orderid, HttpServletResponse response) throws
            IOException, AlipayApiException {
//        String currentUserId = BaseContext.getCurrentUserId();
        // 实例化客户端,填入所需参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
//        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        // 在公共参数中设置回跳和通知地址
        request.setReturnUrl(aliPayConfig.getRETURN_URL());
        request.setNotifyUrl(aliPayConfig.getNOTIFY_URL());
        // 根据订单编号,查询订单相关信息
//        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("orderid",orderid);
        Orders order = ordersMapper.selectByid(orderid);
//        System.out.println(order);
        // 商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = order.getOrderid().toString();
        // 付款金额，必填
        // String total_amount = order.getSetmeal().getPrice().toString();
        String total_amount = setmealMapper.selectdetailById(order.getSmid()).getPrice().toString();
//        String total_amount = "0.01";
        // 订单名称，必填
        String subject = "熙心健康体检";
        // 商品描述，可空
        String body ="";
        request.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                        + "\"total_amount\":\"" + total_amount + "\","
                        + "\"subject\":\"" + subject + "\","
                        + "\"body\":\"" + body + "\","
                        + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String form = "";
        form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        System.out.println(alipayClient.pageExecute(request));
        response.setContentType("text/html;charset=" + aliPayConfig.getCHARSET());
        response.getWriter().write(form);// 直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }

    @GetMapping(value = "/returnUrl")
    public void returnUrl(HttpServletRequest request, HttpServletResponse
            response)
            throws IOException, AlipayApiException {
        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr +
                        values[i] + ",";
            }
            // 解决乱码
            valueStr = new String(valueStr.getBytes(StandardCharsets.UTF_8),
                    StandardCharsets.UTF_8);
            params.put(name, valueStr);
        }

//        System.out.println(params);// 查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                aliPayConfig.getALIPAY_PUBLIC_KEY(), aliPayConfig.getCHARSET(),
                aliPayConfig.getSIGN_TYPE()); // 调用SDK验证签名
        // 验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new
                    String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

            // 支付宝交易号
            String trade_no = new
                    String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

            // 付款金额
            String total_amount = new
                    String(request.getParameter("total_amount").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

            System.out.println("商户订单号 = " + out_trade_no);
            System.out.println("支付宝交易号 = " + trade_no);
            System.out.println("付款金额 = " + total_amount);

            // 支付成功，修改支付状态
            Orders orders = new Orders();
            orders.setOrderid(Integer.valueOf(out_trade_no));
            orders.setState(2);
            System.out.println(orders);
            int a = ordersMapper.updateOrderState(orders.getOrderid(),2);
            System.out.println(a);
            response.sendRedirect("http://localhost:5173/appointmentSuccess");
        }else{
            response.sendRedirect("http://localhost/appointmentFail");
        }
    }
}
